import { reactive, ref, watch, ExtractPropTypes } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import ajax from "@/util/request";
import { setupInsertReturn } from "../setup";

/**
 * 获取提交表单数据
 * @param formData 
 * @returns 
 */
function getFormDataFun(formData: object): object {
    return { ...formData };
}


/**
 * 返回一个方法，调用后获取增加组件所需要用到的属性和方法
 * @param modelName 
 * @param props props对象，需要使用defineProps创建后传入
 * @param emits emits对象，需要使用defineEmits创建后传入
 * @param formRules 
 * @param insertURL 
 * @returns 
 */
function setupInsert({ modelName,
    props,
    emits,
    formRules,
    insertURL = `/${modelName}/insert`,
    pk = `t_${modelName}_pk`,
    getFormData = getFormDataFun,
    success}:
    {
        modelName: string,
        props: Readonly<ExtractPropTypes<any>>,
        emits: any,
        formRules: FormRules,
        insertURL?: string,
        pk?: string,
        getFormData?: (obj: any) => any,
        success?: (updateData: Array<any> | undefined) => void
    }
): setupInsertReturn {

    let updateData: Array<any> | undefined;

    const myForm = ref<FormInstance>();
    const formData = reactive<IStringKey>({});

    const rules = reactive<FormRules>(formRules);

    /**
     * 清空表单
     * @param myForm 表单对象
     */
    function handleClear(myForm: FormInstance) {
        if (myForm) {
            myForm.resetFields();
        }
    }

    watch(
        () => props.modelValue,
        () => (updateData = undefined)
    );

    /**
     * 关闭组件
     */
    function handleClose() {
        emits("close", updateData);
    }

    /**
     * 提交增加
     * @param myForm 表单对象
     */
    function handleInsert(myForm: FormInstance) {
        myForm.validate((valid) => {
            if (!valid) {
                return;
            }
            // 提交的参数
            const postData = getFormData(formData);
            ajax({ url: insertURL, data: postData }).then((res) => {
                if (res.data.code > 0) {
                    myForm.resetFields();
                    alert({ type: "success", message: "增加成功" });
                
                    if (!updateData) {
                        updateData = [];
                    }
                
                    // 把自动生成主键填充回来
                    if (res.data[pk]) {
                        postData[pk] = res.data[pk];
                    }
                    updateData.push(postData);
                    if (success) {
                        success(updateData);
                    }
                }
            });
        });
    }

    return {
        rules, myForm, formData, handleClear, handleClose, handleInsert
    }
}

export default setupInsert;